import BuildForm from '@/components/BuildForm/BuildForm';
import FormattedMessageCustom from '@/components/FormattedMessageCustom/FormattedMessageCustom';
import PayType from '@/components/PayType/PayType';
import UserInfo from '@/components/UserInfo/UserInfo';
import VipPopup from '@/components/VipPopup/VipPopup';
import { getReleaseDetail, saveJoinOrder } from '@/servers/api/order';
import { formFormat } from '@/utils';
import {
    FormattedMessage,
    getLocale,
    history,
    useIntl,
    useLocation,
    useModel,
} from '@umijs/max';
import { Button, Spin, Typography, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { mapForm, mapFormItems } from '../buildFormItems';
import { getFormItems } from './formItem';
type IParams = {
    release_id: number;
    type: string;
};
const BuildOrder: React.FC = () => {
    const location = useLocation();
    const lang = getLocale();
    const intl = useIntl();
    const state = location.state as IParams;
    const [release_detail, setrelease_detail] = useState();
    const { initialState } = useModel('@@initialState');
    const { auth, isAuthName } = initialState as IGlobal.IInitialState;
    const { authModal } = useModel('useUser');
    const formItems = useRef();
    const form = useRef();
    const releaseType = useRef<string>();
    const [loading, setloading] = useState(false);
    const [vipShow, setvipShow] = useState(false);
    const [showPayType, setshowPayType] = useState(false); //支付弹框
    const pay_type = useRef(''); //支付方式
    function getReleaseDetailFun() {
        setloading(true);
        getReleaseDetail({
            release_id: state.release_id,
            type: state.type,
        }).then((response) => {
            const res = response.data;
            if (res.length === 0) {
                message.error('竞标信息错误');
                setTimeout(() => {
                    history.replace('/home');
                }, 2000);
                return false;
            }
            formItems.current = getFormItems(state.type, res);
            setrelease_detail(res);
            const formDetail = {
                is_margin: res.is_margin,
                margin_amount: res.margin_price,
                files: [],
                images: [],
                videos: [],
                price_unit: '元',
                number_unit: res['number_unit'],
                car_category_id: {
                    value: 0,
                    text: '',
                    type: 'release_transport',
                },
                product_address: {
                    country: '',
                    province: 0,
                    city: 0,
                },
            };
            mapFormItems(formItems.current, formDetail, intl).then((mapRes) => {
                formItems.current = mapRes;
            });
            mapForm(formItems.current, state.release_id).then((res) => {
                form.current = res;
            });
            setloading(false);
        });
    }
    function getShowMsg() {
        if (!release_detail) return;
        if (releaseType.current === '运输') {
            let str = '';
            if (release_detail.release_type === '1') {
                str = intl.formatMessage({ id: '有车求货' });
            } else if (release_detail.release_type === '2') {
                str = intl.formatMessage({ id: '有货求车' });
            } else {
                str = intl.formatMessage({ id: '人力捎货' });
                if (release_detail.human_type === '1') {
                    str += '-' + intl.formatMessage({ id: '货源信息' });
                } else {
                    str += '-' + intl.formatMessage({ id: '我要带货' });
                }
            }
            return intl.formatMessage({ id: releaseType.current }) + '-' + str;
        } else {
            return intl.formatMessage({ id: releaseType.current });
        }
    }
    const [currentParams, setcurrentParams] = useState<IBuildForm.IDefault>();
    function onFinish(val: IBuildForm.IDefault) {
        setcurrentParams(val);
        const params = formFormat(val, formItems.current);
        if (!!auth && auth.level > 0) {
            if (auth.auth.indexOf('join') === -1) {
                // 会员免费参与,不限制
                if (auth.join_num === 0 || auth.join_num < 1) {
                    setvipShow(true);
                    // 弹出vip购买弹窗
                    return false;
                } else {
                    if (isAuthName?.status !== 2) {
                        authModal(
                            intl.formatMessage({ id: 'authText' }),
                            intl.formatMessage({ id: '立即认证' }),
                            intl.formatMessage({ id: '继续使用' }),
                        );
                        return;
                    }
                }
            }
        } else {
            if (!!auth && (auth.join_num === 0 || auth.join_num < 1)) {
                setvipShow(true);
                // 弹出vip购买弹窗
                return false;
            }
        }
        // this.form.price_unit = this.release_detail.price_unit
        // 判断是否要交保证金
        // if (this.form.is_margin === '2') {
        //     that.$u.toast(that.$t('该竞标需要缴纳保证金，缴纳成功后即可参与成功'))
        // }

        // 支付环境判断
        if (params.is_margin === '2') {
            if (
                !release_detail.margin_price ||
                release_detail.margin_price * 1 === 0
            ) {
                params.is_margin = '1';
            } else {
                if (lang === 'zh-CN') {
                    if (pay_type.current === '') {
                        setshowPayType(true);
                        return;
                    }
                } else {
                    params.is_margin = '1';
                }
            }
        }
        console.log(params);
        // return;
        setloading(true);
        saveJoinOrder({
            ...params,
            type: state.type,
            release_id: state.release_id,
            openid: '',
            speed_unit: release_detail?.speed_unit,
            id: '',
            pay_type: pay_type.current,
            method: 'web',
        })
            .then(() => {
                setloading(false);
                message.success(
                    intl.formatMessage({ id: '操作成功' }),
                );
                message.error(
                    '开发中...请移步至小程序或移动端进行支付！本次竞标保证金为0',
                );
                history.push('/order');
            })
            .catch((err) => {
                message.error(err.msg);
                setloading(false);
            });
    }
    useEffect(() => {
        if (state.release_id && state.type) {
            getReleaseDetailFun();
            if (state.type === 'goods') {
                releaseType.current = '货物';
            } else if (state.type === 'transport') {
                releaseType.current = '运输';
            } else if (state.type === 'crossborder') {
                releaseType.current = '跨境货代';
            } else if (state.type === 'professional') {
                releaseType.current = '专业代办';
            }
        }
    }, [state]);
    return (
        <Spin spinning={loading}>
            <UserInfo
                info={release_detail?.userInfo}
                showInfoBtn={false}
                type={state.type}
                release_id={release_detail?.id}
            ></UserInfo>
            <Typography.Title level={5}>
                <FormattedMessage id="竞标信息"></FormattedMessage>
                <Typography.Text style={{ marginLeft: 30 }}>
                    <FormattedMessage id="参与类型"></FormattedMessage>-{' '}
                    {getShowMsg()}
                </Typography.Text>
            </Typography.Title>

            <BuildForm
                formItems={formItems.current}
                value={form.current}
                onFinish={onFinish}
            >
                <Button type="primary" htmlType="submit">
                    <FormattedMessageCustom id="参与竞标"></FormattedMessageCustom>
                </Button>
            </BuildForm>
            <VipPopup
                vipShow={vipShow}
                onChange={() => {
                    setvipShow(false);
                }}
            ></VipPopup>
            <PayType
                showPayType={showPayType}
                setshowPayType={setshowPayType}
                change={(e: string) => {
                    pay_type.current = e;
                    onFinish(currentParams);
                    setshowPayType(false);
                }}
            ></PayType>
        </Spin>
    );
};
export default BuildOrder;
